import Taro, { eventCenter, getCurrentInstance } from '@tarojs/taro'
import React, { Component, memo } from 'react'
import { Image, Text, View, MovableView, MovableArea } from '@tarojs/components';
import { Cell, Button, Toast, Popup } from '@antmjs/vantui'
import { getRiskData, submitEligibleApproval, checkWalletBindEligibleInvest, getWalletEligibleInvest, syncWalletElilgibleInvest, } from "@/services/api/eligible_investors"
import { findMapsByFieldNameAndDictItemValue } from '@/services/api/common';
import { stringifyUrl } from 'query-string';
import { getPersonalCertiInfo } from '@/services';
import './index.scss'


class EligibleInvestorsHome extends Component<any, any> {

  config = {
    navigationBarTitleText: '合格投资者确认'
  }

  state = {
    data: {},
    otherInfo: {},
    reviewButtonName: '提交审核',
    reviewButtonDisabled: false,
    syncButtonName: '已同步',
    syncButtonNameDisabled: false,
    showPopUP: false,
    name: '',
    isJG: false
  }

  // useEffect(() => {
  //     getRiskData();
  // }, [])

  constructor(props) {
    super(props);
  }

  // 建议在页面初始化时把 getCurrentInstance() 的结果保存下来供后面使用，
  // 而不是频繁地调用此 API
  $instance = getCurrentInstance()

  componentWillMount() {
    this.getRiskData(true);
    const onShowEventId = this.$instance.router?.onShow ?? ''
    // 监听
    eventCenter.on(onShowEventId, this.onShow)
  }

  /**
   * 页面
   */
  onShow = () => {
    console.log('onShow')
    const { data } = this.state;
    if (Object.keys(data)) {
      this.getRiskData(false);
    }
  }


  componentDidMount() {
    console.log("componentDidMount");
  }
  componentWillReceiveProps(nextProps, nextContext) {
    console.log("componentWillReceiveProps");
  }
  componentWillUnmount() {
    console.log("componentWillUnmount");
  }

  componentDidShow() {
    console.log("componentDidShow");
  }


  /**
   * 请求 列表数据的总入口
   * @returns
   */
  getRiskData(showDialog) {
    const params = this.$instance.router?.params;
    // 是机构
    if (params != null && params['isJG'] === '1') {
      this.requestGetJgRiskData(showDialog)
      Taro.setNavigationBarTitle({
        title: '合格投资者承偌'
      })
    } else {
      this.requestGetPersonRiskData()
      Taro.setNavigationBarTitle({
        title: '合格投资者确认'
      })
    }
  }

  /**
   * 请求机构的合格投资者列表数据
   */
  requestGetJgRiskData(showDialog) {
    getRiskData().then(resp => {
      const data = resp.data
      if (resp.code === 200) {
        this.getReviewButtonStatus(data)
        this.judegeHaveSynchronizeTddxData(showDialog)
      }
    })
  }

  /**
  * 请求个人的合格投资者列表数据
  */
  requestGetPersonRiskData() {
    getWalletEligibleInvest().then(resp => {
      const data = resp.data
      if (resp.code === 200) {
        this.getPersonStatus(data);
      }
    })
  }

  /**
   * 获取个人的状态
   * @param data
   */
  getPersonStatus(data) {
    const params = this.$instance.router?.params;
    if (params != null && params['isJG'] !== null) {
      data['isJG'] = params['isJG']
    }
    this.setState({ data: data.data, otherInfo: data.otherInfo, isJG: data['isJG'] === '1' ? true : false })
  }


  /**
   * 获取审核按钮信息
   * @param data
   */
  getReviewButtonStatus(data) {
    var tempButtomName = '', tempButtonDisabled = false
    if (data.investConfirmAuthStatus == 1) {
      tempButtomName = '提交审核'
      tempButtonDisabled = this.judegeClick(data);
    } else if (data.investConfirmAuthStatus == 2) {
      tempButtomName = '审核通过';
      tempButtonDisabled = true;
    } else if (data.investConfirmAuthStatus == 3) {
      tempButtomName = '提交审核';
      tempButtonDisabled = this.judegeClick(data);
    } else if (data.investConfirmAuthStatus == 4) {
      tempButtomName = '待审核';
      tempButtonDisabled = false;
    } else if (data.investConfirmAuthStatus == 5) {
      tempButtomName = '提交审核';
      tempButtonDisabled = this.judegeClick(data);
    }
    const params = this.$instance.router?.params;
    if (params != null && params['isJG'] !== null) {
      data['isJG'] = params['isJG']
    }

    this.setState({ data: data, reviewButtonName: tempButtomName, reviewButtonDisabled: tempButtonDisabled, isJG: data['isJG'] === '1' ? true : false })
  }


  /**
   * 判断按钮的状态
   * @param data
   * @returns
   */
  judegeClick(data) {
    return (data.investorClass != -1 &&
      (data.investConfirmAttachment ?? '').isNotEmpty &&
      (data.quesInvestNum ?? 0) > 0 &&
      (data.infoFillingStatus ?? 0) == 2 &&
      (data.assetAttachment ?? '').isNotEmpty &&
      data.answerId != '0')
      ? true
      : false;
  }


  /**
   * 是否存在同步特定对象
   * @returns
   */
  judegeHaveSynchronizeTddxData(showDialog) {
    const { data } = this.state;
    console.log(data);

    if (data?.digitalCertiStatus != 2) {
      return
    }
    checkWalletBindEligibleInvest().then(resp => {
      const version = resp.data
      if (resp.code === 200) {
        if (version && version > data['version'] || data['dataSource'] === '1' || data['dataSource'] === 1) {
          this.setState({
            syncButtonName: '已同步',
            syncButtonNameDisabled: true,
          })
        } else {
          this.setState({
            syncButtonName: '授权同步',
            syncButtonNameDisabled: false,
          })
        }

        if (version && version > data['version'] &&
          (data['investConfirmAuthStatus'] == 1 ||
            data['investConfirmAuthStatus'] == 3) &&
          showDialog) {
          this.synchronizeTddxData();
        }
      }
    })
  }


  /**
   * 展示弹窗信息 - 获取
   */
  synchronizeTddxData() {
    getPersonalCertiInfo().then((resp) => {
      if (resp.code === 200) {
        this.setState({ showPopUP: true, name: resp.data['name'] });
      }
    })
  }


  /**
   * 提交审核
   */
  submitEligibleApproval() {
    submitEligibleApproval().then(resp => {
      const data = resp.data
      console.log(data);
      if (resp.code === 200) {
        /// 返回到列表页面或者 到下一步页面
        this.requestGetJgRiskData(false)
      }
    })
  }

  gotoFxcp() {

  }

  /**
   * 关闭弹窗
   */
  onClose() {
    this.setState({ showPopUP: false });
  }

  /**
   * 同步
   */
  onSubmit() {
    syncWalletElilgibleInvest().then(resp => {
      const data = resp.data
      console.log(data);
      this.setState({ showPopUP: false, syncButtonNameDisabled: true });

      if (resp.code === 200) {
        this.getReviewButtonStatus(data)
      }
    })
  }





  render() {
    const { safeArea } = Taro.getSystemInfoSync();
    const { data, otherInfo, reviewButtonDisabled, reviewButtonName, syncButtonNameDisabled, syncButtonName, showPopUP, name, isJG } = this.state;


    const renderLeftArea = ({ iconName, name }) => {
      return (
        <View className='left-area'>
          <Image src={require(`@/assets/icons/eligible_investors/${iconName}.svg`)} style={{ width: 20, height: 20 }} />
          <View className='title'>{name}</View>
        </View>
      )
    }

    const renderRightArea = ({ name }) => {

      var className = '', rightName = '';

      if (name == '投资者类型') {
        className = 'status-none';
        rightName = '请选择'

        if (data['investorClass'] == 1) {
          className = 'status-done';
          rightName = '自然人-普通投资者'
        } else if (data['investorClass'] == 2) {
          className = 'status-done';
          rightName = '自然人-专业投资者'
        } else { // -1
          className = 'status-none';
          rightName = '请选择'
        }
      } else if (name == '合格投资者承偌') {
        if (data['investConfirmAttachment'] && data['investConfirmAttachment'].length > 0) {
          rightName = '已签署';
          className = 'status-border-done';
        } else {
          rightName = '未签署';
          className = 'status-border-none';
        }

      } else if (name == '风险测评') {
        if (data['quesInvestNum'] && data['quesInvestNum'] > 0) {
          const maps = findMapsByFieldNameAndDictItemValue('risk_accept', data['riskAccept']);
          rightName = `${data['quesInvestNum']}分 |  ${maps != null ? maps['dictItemName'] : ''}`;
          className = 'status-done';
        } else {
          rightName = '未测评';
          className = 'status-border-none';
        }
      } else if (name == '投资者信息表填写及签署') {
        if (isJG) {
          if (data['infoFillingStatus'] == 2) {
            rightName = '已完成';
            className = 'status-border-done';
          } else {
            rightName = '未填写';
            className = 'status-border-none';
          }
        }
      } else if (name == '投资者证明材料上传') {
        if (isJG) {
          if (data['assetAttachment'] && data['assetAttachment'].length > 0) {
            rightName = '已上传';
            className = 'status-border-done';
          } else {
            rightName = '未上传';
            className = 'status-border-none';
          }
        }
      }


      return (
        <View className='right-area'>
          <View className={`title ${className}`}>{rightName}</View>
          <Image src={require('@/assets/icons/public/public_arrow_right.svg')} style={{ width: 18, height: 18 }} />
        </View>
      )
    }
    return (
      <MovableArea className='detailPage'>

        <View className='page'>

          <View className='list' >
            <Cell renderTitle={renderLeftArea({ iconName: 'eligible_investors_list_type', name: '投资者类型' })} renderRightIcon={renderRightArea({ name: '投资者类型' })} titleStyle={{ fontSize: '16px' }} border linkType='navigateTo' url={stringifyUrl({ url: `/eligible_investors/type/index`, query: data }, { encode: false })} />

            {
              isJG ?
                <Cell renderTitle={renderLeftArea({ iconName: 'eligible_investors_list_hgtzzcr', name: '合格投资者承偌' })} renderRightIcon={renderRightArea({ name: '合格投资者承偌' })} titleStyle={{ fontSize: '16px' }} border linkType='navigateTo' url={`${stringifyUrl({ url: '/eligible_investors/commitment/index', query: data }, { encode: false })}`} />
                : null
            }
            {/* `/eligible_investors/risk_assessment/index` */}

            {
              isJG ?

                (data['answerId'] && data['answerId'] !== '0') ?
                  <Cell renderTitle={renderLeftArea({ iconName: 'eligible_investors_list_fxcp', name: '风险测评' })} renderRightIcon={renderRightArea({ name: '风险测评' })} titleStyle={{ fontSize: '16px' }} border linkType='navigateTo' url={stringifyUrl({ url: `/eligible_investors/risk_assessment/detail/index`, query: data }, { encode: false })} />
                  :
                  <Cell renderTitle={renderLeftArea({ iconName: 'eligible_investors_list_fxcp', name: '风险测评' })} renderRightIcon={renderRightArea({ name: '风险测评' })} titleStyle={{ fontSize: '16px' }} border linkType='navigateTo' url={stringifyUrl({ url: `/eligible_investors/risk_assessment/index`, query: data }, { encode: false })} />
                : null
            }
            {/* <Cell renderTitle={renderLeftArea({ iconName: 'eligible_investors_list_xxbtx', name: '投资者信息表填写及签署' })} renderRightIcon={renderRightArea({ name: '投资者信息表填写及签署' })} titleStyle={{ fontSize: '16px' }} border linkType='navigateTo' url={`${stringifyUrl({ url: '/eligible_investors/information_table/index', query: Object.assign(data, otherInfo) }, { encode: false })}}`} />
            <Cell renderTitle={renderLeftArea({ iconName: 'eligible_investors_list_tzzzmclsc', name: '投资者证明材料上传' })} renderRightIcon={renderRightArea({ name: '投资者证明材料上传' })} titleStyle={{ fontSize: '16px' }} border={false} linkType='navigateTo' url={`${stringifyUrl({ url: '/eligible_investors/evidence/index', query: data }, { encode: false })}}`} /> */}
            {/* <Cell renderTitle={renderLeftArea({ iconName: 'eligible_investors_list_type', name: '下一步' })} renderRightIcon={renderRightArea({ name: '下一步' })} titleStyle={{ fontSize: '16px' }} border={false} linkType='navigateTo' url='/eligible_investors/next_step/index' /> */}
          </View>

          {/* {
                        isJG ?
                            <View className='bottom' style={{ paddingBottom: safeArea.top + 12 }}>
                                <Button disabled={syncButtonNameDisabled} className='left-button' >{syncButtonName}</Button>
                                <Button disabled={reviewButtonDisabled} className='right-button' >{reviewButtonName}</Button>
                            </View> : null
                    } */}

          <Popup show={showPopUP} position='bottom' onClose={this.onClose.bind(this)}>
            <View className='ei-popup'>
              <View className='tip'>
                <Text>一道投</Text>
                <View></View>
                <Text>申请授权</Text>
              </View>

              <Text className='title-1'>获取您已上链的合格投资者认证信息</Text>
              <Text className='title-2'>快速录入，免除重复填写合格投资者相关内容，但会覆盖当前您已录入的内容。 </Text>
              <View className='id-name'>
                <Text>{name}</Text>
                <Text>实名信息人</Text>
              </View>
              <View className='button'>
                <Button className='button-item left-button' onClick={this.onClose.bind(this)}>取 消</Button>
                <Button className='button-item right-button' onClick={this.onSubmit.bind(this)}>确定授权</Button>
              </View>
            </View>

          </Popup>
          <Toast />


          {/* <MovableView
                        y={safeArea.height - 120}
                        x={safeArea.width - 70}
                        className="backHome"
                        direction="all"
                        onClick={e => Taro.switchTab({ url: "/pages/index/index" })}
                    >
                        <View>回到首页</View>
                    </MovableView> */}

        </View>
      </MovableArea >

    );
  }
}

export default memo(EligibleInvestorsHome);

